package serviceImpl;

import bean.Role;
import dao.RoleDao;
import impl.RoleDaoImpl;
import service.RoleService;
import util.DBHelper;
import util.ServerResponseResult;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @classname:RoleServiceImpl
 * @description:
 * @author: Mr.Z
 * @date: 2020/12/30 17:32
 * @version: 0.1
 * @since:1.8
 */
public class RoleServiceImpl implements RoleService {
    @Override
    public ServerResponseResult addRole(Role role, int[] ids) {
        Connection con = DBHelper.getCon();
        try {
            //一个连接一个
            con.setAutoCommit(false);
            RoleDao roleDao = new RoleDaoImpl(con);
            int roleId = roleDao.addRole(role);
            roleDao.addRoleAndPer(roleId, ids);
            con.commit();
            return ServerResponseResult.success();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBHelper.closeResources(con);
        }
        return ServerResponseResult.error();
    }

    //修改角色对应的权限
    @Override
    public ServerResponseResult updateRole(Role role, int[] ids) {
        Connection connection = DBHelper.getCon();
        RoleDao roleDao = new RoleDaoImpl(connection);
        roleDao.updateRoleId(role);

        try {
            if (ids.length != 0) {
                connection.setAutoCommit(false);
                // 先删除角色对应的权限
                roleDao.deleteRoleAndPer(role.getId());
                //添加全部权限
                roleDao.addRoleAndPer(role.getId(), ids);
            }
            connection.commit();
            return ServerResponseResult.success();
        } catch (Exception e) {
            try {
                connection.rollback();
                return ServerResponseResult.error();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBHelper.closeResources(connection);
        }
        return ServerResponseResult.error();


    }
}
